package com.atguigu.gmall.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


/**
 * @author gsy
 * @date 2021年09月06日21:18
 * Description
 */
@Component
public class LoginGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;
    //路径匹配
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public static final String TOKEN = "token";
    //用户登录
    public static final String USER_LOGIN_KEY_PREFIX = "user:login:";

    public static final String LOGINURL="http://passport.gmall.com/login.html?originUrl=";

    //用户临时id
    public static final String USERTEMPID ="userTempId";

    @Value("${url.authUrls}")
    private String[] authUrls;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //取出令牌
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String userId = getUserId(request);
        //判断请求路径是否请求的内部资源 /api/product/inner/getSkuInfo/{skuId}
        String path = request.getURI().getPath();
        if (antPathMatcher.match("/**/inner/**", path)) {
            //内部资源不允许访问
            return out(response, ResultCodeEnum.PERMISSION);
        }
        //校验用户是否要登录
        //结算 提交订单 支付 用户中心 需要登录
        //  /api/order/auth/submitOrder   异步请求
        // /trade.html pay.html 同步请求
        //异步
        if (antPathMatcher.match("/**/auth/**", path) && StringUtils.isEmpty(userId)) {
            //需要登录但没有登录
            return out(response, ResultCodeEnum.LOGIN_AUTH);
        }
        //同步
        for (String authUrl : authUrls) {
            if (path.contains(authUrl) && StringUtils.isEmpty(userId)) {
                //需要登录但没有登录
                //重定向到登录页面 'http://passport.gmall.com/login.html?originUrl='+ encodeURIComponent(window.location.href)
                String url = request.getURI().toString();
                response.setStatusCode(HttpStatus.SEE_OTHER);
                try {
                    response.getHeaders().add(HttpHeaders.LOCATION
                            , LOGINURL+ URLEncoder.encode(url, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return response.setComplete();
            }
        }
        //传递用户真实id
        if (!StringUtils.isEmpty(userId)){
            request.mutate().header("userId",userId);
        }
        //传递用户临时id
        String userTempId = getUserTempId(request);
        request.mutate().header("userTempId",userTempId);
        //放行
        return chain.filter(exchange);
    }
    //获取用户临时id
    private String getUserTempId(ServerHttpRequest request) {
        //用户临时id存在请求头中   异步请求
        String userTempId = request.getHeaders().getFirst(USERTEMPID);
        if (StringUtils.isEmpty(userTempId)){
            //判断是否在Cookie中
            HttpCookie httpCookie = request.getCookies().getFirst(USERTEMPID);
            if(httpCookie!=null){

                userTempId = httpCookie.getValue();
            }

        }
        return userTempId;
    }

    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result<Object> result = Result.build(null, resultCodeEnum);
        //转换成Json字符串然后转成二进制
        byte[] bytes = JSONObject.toJSONBytes(result);
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer buffer = dataBufferFactory.wrap(bytes);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        return response.writeWith(Mono.just(buffer));
    }

    private String getUserId(ServerHttpRequest request) {
        //令牌可能存在Hear中或Cookie中
        String token = request.getHeaders().getFirst(TOKEN);
        //判断header中是否存在
        if (StringUtils.isEmpty(token)) {
            HttpCookie httpCookie = request.getCookies().getFirst(TOKEN);
            //判断Cookie中是否携带token
            if (httpCookie != null) {
                token = httpCookie.getValue();
            }
        }
        //判断token是否存在
        if (!StringUtils.isEmpty(token)) {
            //向redis缓存中取用户id
            //先判断用户id是否存在,存在再去redis中取值
            if (redisTemplate.hasKey(USER_LOGIN_KEY_PREFIX + token)) {
                String userId = (String) redisTemplate.opsForValue().get(USER_LOGIN_KEY_PREFIX + token);
                return userId;
            }
        }
        //未登录
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
